package com.example.hbutliving.util;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

import com.example.hbutliving.BaseTest;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

public class MockUtil extends BaseTest {

    public static final String URL_HEADER="http://127.0.0.1/";

    public static String request(MockHttpServletRequestBuilder requestBuilder,Map<String,String> data,Map<String,String> header){
        if(data!=null){
            data.forEach(requestBuilder::param);
        }
        if(header!=null){
            header.forEach(requestBuilder::header);
        }
        String contentAsString=null;
        try {
            MockHttpServletResponse response = mvc.perform(requestBuilder).andReturn().getResponse();
            response.setCharacterEncoding("utf-8");
            contentAsString=response.getContentAsString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return contentAsString;
    }

    public static String doGet(String url,Map<String,String> data,Map<String,String> header){
        if(data!=null){
            url+="?";
            Set<Map.Entry<String, String>> entrySet = data.entrySet();
            StringBuilder urlBuilder = new StringBuilder(url);
            for (Map.Entry<String, String> entry : entrySet) {
                urlBuilder.append(entry.getKey());
                urlBuilder.append("=");
                urlBuilder.append(entry.getValue());
                urlBuilder.append("&");
            }
            url = urlBuilder.toString();
        }
        MockHttpServletRequestBuilder requestBuilder = get(URL_HEADER+url);
        if(header!=null){
            header.forEach(requestBuilder::header);
        }
        String contentAsString=null;
        try {
            MockHttpServletResponse response = mvc.perform(requestBuilder).andReturn().getResponse();
            response.setCharacterEncoding("utf-8");
            contentAsString=response.getContentAsString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return contentAsString;
    }
}
